package dem1;

import java.util.Arrays;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-04-03
 * Time: 20:16
 */
public class MyArrayList {
    private int[] elem;
    private int usedSize;

    public MyArrayList() {
        this.elem = new int[10];
        this.usedSize = 0;
    }

    public int[] getElem() {
        return elem;
    }

    public int getUsedSize() {
        return usedSize;
    }

    public void display() {
        if (usedSize == 0 || elem == null){
            System.out.println("[]");
            return;
        }
        int[] arr = Arrays.copyOf(elem,usedSize);
        System.out.println(Arrays.toString(arr));
        arr = null;
    }

    private boolean isFull(){
        if (usedSize == elem.length){
            return true;
        }
        return false;
    }

    private void expansion(){
        int[] arr = Arrays.copyOf(elem,elem.length * 2);
        elem = arr;
    }

    public void add(int data) {
        if(isFull()){
            expansion();
        }
        elem[usedSize] = data;
        usedSize++;
    }

    private boolean checkPosInAdd(int pos){
        if (pos > usedSize || pos < 0){
            return false;
        }
        return true;
    }

    public void add(int pos, int data) {
        if (isFull()){
            expansion();
        }
        if(!checkPosInAdd(pos)){
            throw new IndexOutBround("pos超出范围");
        }
        for (int i = usedSize - 1; i >= pos; i--){
            elem[i] = elem[i + 1];
        }
        elem[pos] = data;
        usedSize++;
    }

    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize; i++){
            if (elem[i] == toFind){
                return true;
            }
        }
        return false;
    }

    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++){
            if (elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }

    public int get(int pos) {
        if(!checkPosInAdd(pos)){
            throw new IndexOutBround();
        }
        return elem[pos];
    }

    private boolean isEmpty() {
        if(elem == null || usedSize == 0){
            return true;
        }
        return false;
    }

    public void set(int pos, int value) {
        if (!checkPosInAdd(pos)){
            throw new IndexOutBround();
        }
        elem[pos] = value;
    }

    public void remove(int key) {
        int j = indexOf(key);
        for (int i = j; i < usedSize - 1; i++){
            elem[i] = elem[i + 1];
        }
        usedSize--;
    }

    public void clear() {
        usedSize = 0;
        elem = null;
    }
}
